import React, { useState } from "react";
import { NavBar, Search } from "react-vant";
import { useNavigate } from "react-router";
import http from "../../utils/http";
import Listltem from "../../components/ListItem";

const Index: React.FC = () => {
  const [searchList, setSearchList] = useState([]);
  // 历史记录
  const [hisList, setHisList] = useState<string[]>(
    JSON.parse(localStorage.getItem("his") || "[]")
  );
  const [wd, setWd] = useState("");
  const navigate = useNavigate();

  const handleSearch = async (value: string) => {
    setWd(value);
    // 历史记录去重
    const ind = hisList.lastIndexOf(value);
    if (ind > -1) {
      hisList.splice(ind, 1);
      setHisList(hisList);
    }

    hisList.unshift(value);
    localStorage.setItem("his", JSON.stringify(hisList));
    
    // 添加历史记录
    if (value !== "") {
      const res = await http.get("/api/list", {
        params: {
          wd: value,
        },
      });
      const { data } = res.data;
      setSearchList(data);
    } else {
      setSearchList([]);
    }
  };

  // 清除历史记录
  const handelClear = () => {
    setHisList([]);
    localStorage.setItem("his", JSON.stringify(hisList));
  };
  return (
    <div>
      <NavBar
        title="搜索页"
        leftText="返回"
        onClickLeft={() => navigate("/")}
      />
      <Search
        value={wd}
        placeholder="请输入搜索关键词"
        onSearch={handleSearch}
      />
      <div>
        <h3>
          历史记录 <span onClick={handelClear}>清除</span>
        </h3>
        <ul>
          {hisList.map((item, ind) => (
            <li key={ind} onClick={() => handleSearch(item)}>
              {item}
            </li>
          ))}
        </ul>
      </div>
      <div>
        {searchList.length > 0 &&
          searchList.map((item, ind) => (
            <Listltem item={item} key={ind}></Listltem>
          ))}
      </div>
    </div>
  );
};

export default Index;
